<template>
  <div class="bg-gray size-full min-h-screen flex items-center justify-center">
    <div class="login-container bg-white rounded-lg shadow-xl p-8 w-full max-w-md">
      <div class="text-center mb-8">
        <h1 class="text-2xl font-bold text-gray-800">公司管理系统</h1>
        <p class="text-gray-600 mt-2">请登录您的账户</p>
      </div>

      <form @submit.prevent="handleLogin" class="space-y-6">
        <div>
          <label for="username" class="block text-gray-700 text-sm font-medium mb-2">用户名</label>
          <input
              id="username"
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 box-border"
              required
          />
        </div>

        <div>
          <label for="password" class="block text-gray-700 text-sm font-medium mb-2">密码</label>
          <input
              id="password"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 box-border"
              required
          />
        </div>


        <button
            type="submit"
            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-300"
            :disabled="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <div class="mt-6 text-center text-sm text-gray-600">
        <p>© 2025 公司文档管理系统. 保留所有权利.</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {useQuery} from "@pinia/colada";
import {login} from "../../api/account.ts";
import {ElMessage} from "element-plus"
import {useUserStore} from "../../store/userStore.ts";

const userStore = useUserStore();
let {setUserInfo, getUserInfo} = userStore;

onMounted(() => {
  if (getUserInfo() !== undefined) {
    router.push('/dashboard')
  }
})

interface LoginForm {
  username: string
  password: string
}

export type LoginParams = LoginForm

const router = useRouter()

const loginForm = ref<LoginForm>({
  username: '',
  password: ''
})

const handleLogin = () => {
  refetch();
}

let {isLoading: loading, refetch} = useQuery({
  key: ["login"],
  query: () => login(loginForm.value).then(res => {
    ElMessage.success("登录成功");
    setUserInfo(res)
    router.push({
      path: '/dashboard'
    });
  }),
  enabled: () => false
});
</script>

<style scoped>
.bg-gray {
  background-color: #f3f4f6;
}
</style>